package com.example.androidapp2;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.example.androidapp2.DbClasses.TotalCategoria;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.GridLayoutAnimationController;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MainActivity extends Activity {	
	DbAdapter DbConect;

	private PopUpTarjetas pupTarjeta; 	
	private PopUpConfigu pupConfi;

	//PantallaPrincipal	
	private Button btnResta;
	private EditText txtIngresos;
	private EditText txtEgresos;
	private EditText txtResta;		
	private TextView lblPorcentaje;	
	private TextView lblErrores;
	private ProgressBar skTotal;	
	private RadioButton rdEfectivo;
	private RadioButton rdTarjeta;
	private Spinner spnCategorias;	

	private List<Integer> ValoresAnteriores;

	private Button btnMil;
	private Button btnQuinientos;
	private Button btnCien;
	private Button btnCincuenta;
	private Button btnDiez;
	private Button btnCinco;
	private Button btnUno;
	private Button btnAtras;	

	//Pantalla2
	private GridView grdPorcentajes;

	private Button btnIr;
	private Button btnVolver;

	private ViewFlipper flpView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.view_flipper);
			DBOpen();

			pupTarjeta= new PopUpTarjetas(this);
			pupConfi = new PopUpConfigu(this, DbConect);
			SetControls();
			SetControlValues();
			if(DbConect.GetTotalMovimientos("In")==0)
				pupConfi.show();

			ActualizarProgressBar();
		}catch (Exception e) 
		{
			lblErrores.setText("Error al cargar: "+e.getMessage());	
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) 
	{ 
		if(item.getItemId() == R.id.itmUltimo)
			DbConect.InactivarUltimo();

		ActualizarProgressBar();
		return true;
	}

	public void SetControls()
	{
		btnResta = (Button) findViewById(R.id.btnResta);
		txtIngresos = (EditText) findViewById(R.id.txtIngresos);
		txtEgresos =(EditText) findViewById(R.id.txtEgresos);
		txtResta = (EditText) findViewById(R.id.txtResta);			
		lblPorcentaje = (TextView) findViewById(R.id.lblPorcentaje);			 
		lblErrores = (TextView) findViewById(R.id.lblErrores);
		rdEfectivo = (RadioButton) findViewById(R.id.rdEfectivo);		
		rdTarjeta = (RadioButton) findViewById(R.id.rdTarjeta);
		skTotal = (ProgressBar) findViewById(R.id.skTotal);
		spnCategorias = (Spinner) findViewById(R.id.spnCategorias);	

		btnMil = (Button)  findViewById(R.id.btn1000);
		btnQuinientos = (Button)  findViewById(R.id.btn500);
		btnCien = (Button)  findViewById(R.id.btn100);
		btnCincuenta = (Button)  findViewById(R.id.btn50);
		btnDiez = (Button)  findViewById(R.id.btn10);
		btnCinco = (Button)  findViewById(R.id.btn5);
		btnUno = (Button)  findViewById(R.id.btn1);
		btnAtras = (Button)  findViewById(R.id.btnAtras);
		ValoresAnteriores = new ArrayList<Integer>();

		grdPorcentajes = (GridView) findViewById(R.id.grdPorcentajes);

		btnIr = (Button) findViewById(R.id.btnIr);
		btnVolver = (Button) findViewById(R.id.btnVolver);
		flpView = (ViewFlipper) findViewById(R.id.flpView);					
	}

	public void SetControlValues()
	{
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, ListaCategorias());
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnCategorias.setAdapter(spinnerAdapter);	

		SetListenerBotones(new Button[]{btnMil,btnQuinientos,btnCien,btnCincuenta,btnDiez,btnCinco,btnUno});
	}

	public void CargarPantallaPorcentajes()
	{
		final List<TotalCategoria> list = DbConect.GetTotalesPorCategoria();

		ArrayAdapter<TotalCategoria> gridAdapter = new ArrayAdapter<TotalCategoria>(this,android.R.layout.simple_list_item_2, list){
			@Override			
			public View getView(int position, View convertView, ViewGroup parent)
			{
				int total =DbConect.GetTotalMovimientos("Eg");
				TotalCategoria tt = list.get(position);
				int porcentaje = (tt.Total*100)/total;				
				LayoutInflater li = getLayoutInflater();

				View MyView = li.inflate(R.layout.grd_porcentajes_item, null);
				TextView tv = (TextView)MyView.findViewById(R.id.grd_item_txtDesc);
				tv.setText(tt.Descripcion + "($"+tt.Total+" ~ "+porcentaje + "%): " );

				if(porcentaje<33)
					tv.setTextColor(Color.parseColor("#00FF00"));
				else if (porcentaje>33 && porcentaje<66)
					tv.setTextColor(Color.parseColor("#FFFF00"));
				else
					tv.setTextColor(Color.parseColor("#FF0000"));

				ProgressBar prg = (ProgressBar) MyView.findViewById(R.id.grd_item_prgPorcentaje);
				prg.setMax(total);
				prg.setProgress(tt.Total);				

				return MyView;
			}
		};	
		grdPorcentajes.setAdapter(gridAdapter);		
	}

	public void SetListenerBotones(Button[] btns)
	{
		for (Button bt : btns) {
			bt.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					ClickSumar(((Button)v).getText().toString());
				}
			});
		}

		btnResta.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				if(!txtResta.getText().toString().equals("")){
					GuardarMovimiento(Integer.parseInt(txtResta.getText().toString()),"Eg",GetFecha(),GetMedio(),String.valueOf(spnCategorias.getSelectedItemId()+1));
					ActualizarProgressBar();
					txtResta.setText("");
					ValoresAnteriores = new ArrayList<Integer>();
				}
			}
		});

		btnIr.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				try{				
					CargarPantallaPorcentajes();
					flpView.setInAnimation(inFromRightAnimation());
					flpView.setOutAnimation(outToLeftAnimation());
					flpView.showNext();					
				}catch(Exception e)
				{
					lblErrores.setText(e.getMessage());					
				}
			}
		});

		btnVolver.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				try{					
					flpView.setInAnimation(inFromLeftAnimation());
					flpView.setOutAnimation(outToRightAnimation());
					flpView.showPrevious();					
				}catch(Exception e)
				{
					lblErrores.setText(e.getMessage());					
				}
			}
		});

		btnAtras.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(ValoresAnteriores.size()>0 && !ValoresAnteriores.get(ValoresAnteriores.size()-1).equals(0))
				{
					txtResta.setText(String.valueOf(ValoresAnteriores.get(ValoresAnteriores.size()-1)));
					ValoresAnteriores.remove(ValoresAnteriores.size()-1);
				}
				else
					txtResta.setText("");
			}
		});

		final RadioButton rdTarjeta = (RadioButton) findViewById(R.id.rdTarjeta);
		((RadioGroup) findViewById(R.id.radioGroup1)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if(rdTarjeta.isChecked())
					CargarPopUpTarjeta();
			}
		});		
	}



	public void ClickSumar(String txt)
	{		

		int total=0;
		if(txtResta.getText().toString().length()>0)
			total = Integer.parseInt(txtResta.getText().toString());
		ValoresAnteriores.add(total);
		total += Integer.parseInt(txt.substring(1));
		txtResta.setText(String.valueOf( total));
	}

	public void CargarPopUpTarjeta()
	{	
		pupTarjeta.SetListenerBotonesPopUpTarjetas();
		pupTarjeta.show();
	}


	public void GuardarMovimiento(int txt, String tipo, String fecha, String medio, String categoria) {
		try {
			DbConect.InsertMovimiento(txt, tipo, fecha,medio,categoria);
		}catch (Exception e) {
			lblErrores.setText("Error al cargar: "+e.getMessage());
		}
	}

	public void ActualizarProgressBar()
	{	
		int ingreso = DbConect.GetTotalMovimientos("In");
		int egreso = DbConect.GetTotalMovimientos("Eg");

		txtIngresos.setText("$"+String.valueOf(ingreso));
		txtEgresos.setText("$"+String.valueOf(egreso));

		double porcentaje = (ingreso>0)?100-((egreso * 100)/ingreso):0;
		long pesos = ingreso-egreso;

		if(pesos<0)
			lblPorcentaje.setTextColor(Color.parseColor("#E73F2F"));
		else
			lblPorcentaje.setTextColor(Color.parseColor("#9DCD39"));		

		lblPorcentaje.setText("$"+String.valueOf(pesos) +" ~ "+String.valueOf(porcentaje) + "%");

		/*Resources res = this.getResources();
		if(porcentaje<=33)
			skTotal.setProgressDrawable(res.getDrawable(R.drawable.prg_verde));
		else if (porcentaje>33 && porcentaje<66)
			skTotal.setProgressDrawable(res.getDrawable(R.drawable.prg_amarillo));
		else
			skTotal.setProgressDrawable(res.getDrawable(R.drawable.prg_rojo));*/

		skTotal.setMax(100);
		skTotal.setProgress((int) porcentaje);
		/*if(egreso<=ingreso)
			skTotal.setProgress(egreso);		
		else
			skTotal.setProgress(ingreso);*/
		skTotal.setEnabled(false);
	}

	private String GetMedio()
	{
		String tipo = "";
		if(rdEfectivo.isChecked())
			tipo = "EFT";		
		else if(rdTarjeta.isChecked())
			tipo="TRJ";

		return tipo;
	}

	private String GetFecha()
	{
		Calendar c = Calendar.getInstance(); 

		String fecha = (
				((c.get(Calendar.DATE)<10)?"0"+String.valueOf( c.get(Calendar.DATE)):String.valueOf( c.get(Calendar.DATE)))+
				((c.get(Calendar.MONTH)+1<10)?"0"+String.valueOf( c.get(Calendar.MONTH)+1):String.valueOf( c.get(Calendar.MONTH)+1))+
				((c.get(Calendar.YEAR)<10)?"0"+String.valueOf( c.get(Calendar.YEAR)):String.valueOf( c.get(Calendar.YEAR)))+
				((c.get(Calendar.HOUR_OF_DAY)<10)?"0"+String.valueOf( c.get(Calendar.HOUR_OF_DAY)):String.valueOf( c.get(Calendar.HOUR_OF_DAY)))+
				((c.get(Calendar.MINUTE)<10)?"0"+String.valueOf( c.get(Calendar.MINUTE)):String.valueOf( c.get(Calendar.MINUTE)))
				);

		return fecha;
	}

	private List<String> ListaCategorias()
	{
		return DbConect.GetCategorias("spnCategorias");	
	}

	private Animation inFromRightAnimation() {
		Animation inFromRight = new TranslateAnimation(		
				Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,		
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f		
				);
		inFromRight.setDuration(500);		
		inFromRight.setInterpolator(new AccelerateInterpolator());

		return inFromRight;
	}

	private Animation outToLeftAnimation() {
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
				);
		outtoLeft.setDuration(500);
		outtoLeft.setInterpolator(new AccelerateInterpolator());

		return outtoLeft;
	}

	private Animation inFromLeftAnimation() {		
		Animation inFromLeft = new TranslateAnimation(		
				Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,		
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f		
				);

		inFromLeft.setDuration(500);		
		inFromLeft.setInterpolator(new AccelerateInterpolator());

		return inFromLeft;		
	}

	private Animation outToRightAnimation() {		
		Animation outtoRight = new TranslateAnimation(		
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,		
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f		
				);

		outtoRight.setDuration(500);		
		outtoRight.setInterpolator(new AccelerateInterpolator());

		return outtoRight;		
	}

	private void DBOpen(){
		DbConect= new DbAdapter(this);

		try {
			DbConect.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}

		try {
			DbConect.openDataBase();
		}catch(SQLException sqle){
			throw sqle;
		}
	}
}